﻿Imports System
Imports IDServer
Imports System.Threading.Thread
Imports System.IO
Imports System.String
Imports Microsoft.VisualBasic
Imports Microsoft.VisualBasic.VBMath
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports CalendarColumn
Imports System.Configuration

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

Public Class Frm_System

    Implements IDServer.IDServer.IDServer

    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Public mDS As DataSet  '新增表單的的資料集
    Private dsBSC As DataSet  '存放公共資料
    Private ds As New DataSet  '瀏覽表單的資料集
    Private dsTemp As New DataSet '更新剩餘數量及剩餘金額時用
    Private strOriginalNum As String = ""
    Private strOrFNum As String = ""
    Private strOriginalFSaleOrdeNo As String = "" '原始銷售合同
    Private tempDS As New DataSet
    Private dsINV As New DataSet
    Private bFind As Boolean
    Private IsCheck As Boolean = True  '是否檢查發票數量、金額的合法性
    Private Fields As String
    Private WithEvents MainFrom As Frm_MainForm

    Private mPoint As Point
    Private X, Y As Integer

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainFrom
        End Get
        Set(ByVal value As Frm_MainForm)
            MainFrom = value
        End Set
    End Property

#Region "inteface define"

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        Try
            If AddEnable = False Then
                MessageBox.Show(My.resources.notallowadd, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Me.Cursor = Cursors.WaitCursor

            ClearText()
            ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd

            EnabledControls(True)

            SetButton(ButtonType.Add, False)

            Me.cmbFCategory.Focus()


        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox("ActionAdd：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Try

            ClearText()
            EnabledControls(False)

            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp

            If ds Is Nothing Then
                Exit Function
            End If

            IsFind = FindRecord()
            SetButton(ButtonType.Cancel, IsFind)

            If ds.Tables.Count = 0 Then
                Exit Function
            End If
            If Me.ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            IsFind = FindRecord()
            SetButton(ButtonType.Cancel, IsFind)

        Catch ex As Exception
            MsgBox("ActionCancel：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)

        Finally
            Me.dgv1_CurrentCellChanged(Nothing, Nothing)

        End Try
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        Try
            If EditEnable = False Then
                MessageBox.Show(My.resources.NotAllowEidt, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            If Me.dgv1.SelectedCells.Count = 0 Then
                Exit Function
            End If

            ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
            EnabledControls(True)
            SetButton(ButtonType.Edit, False)
            Me.dgv1_CurrentCellChanged(Nothing, Nothing)
            Me.cmbFCategory.Focus()


        Catch ex As Exception
            MsgBox("ActionEdit:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Try
            Me.Cursor = Cursors.WaitCursor
            If FindRecord() = False Then
                Exit Function
            Else

                Dim tb As DataTable '猁換腔桶
                'tb = CType(Me.dgrdCustomer.DataSource, DataTable)

                Dim dsTemp As DataSet = ds.Copy
                '將列名改為中文名
                For I As Integer = Me.dgv1.Columns.Count - 1 To 0 Step -1
                    Dim strName As String = Me.dgv1.Columns(I).Name
                    dsTemp.Tables(0).Columns(strName).Caption = Me.dgv1.Columns(strName).HeaderText
                    '移除不需要顯示的列
                    If Me.dgv1.Columns(I).Visible = False Then
                        dsTemp.Tables(0).Columns.Remove(strName)
                    End If
                Next

                '將表名改為中文名
                dsTemp.Tables(0).TableName = "系統參數設置"
                SaveXls(dsTemp)

            End If
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox("ActionExport：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            dgv1.CurrentCell = dgv1.Rows(0).Cells(0)


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast
        Try
            If ds Is Nothing Then
                Exit Function
            End If
            Dim row As Integer = Me.dgv1.CurrentCell.RowIndex

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            If Me.dgv1.RowCount > 0 Then
                dgv1.CurrentCell = dgv1.Rows(dgv1.Rows.Count - 1).Cells(0)
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            Dim row As Integer = Me.dgv1.CurrentCell.RowIndex

            If Me.dgv1.RowCount > 0 And Me.dgv1.CurrentRow.Index < Me.dgv1.Rows.Count - 1 Then
                dgv1.CurrentCell = dgv1.Rows(dgv1.CurrentRow.Index + 1).Cells(0)
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            Dim row As Integer = Me.dgv1.CurrentCell.RowIndex

            If Me.dgv1.RowCount > 0 And Me.dgv1.CurrentRow.Index > 0 Then
                dgv1.CurrentCell = dgv1.Rows(dgv1.CurrentRow.Index - 1).Cells(0)
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize
        Try

            Dim sql As String
            Dim dsSql As New DataSet

            Dim FCategory, FKey, FValue, FDescription, strFReadonly As String
            Dim OriFCategory, OriFKey, OriFValue As String
            Dim FReadonly As Int16

            FCategory = Me.cmbFCategory.Text & ""
            FKey = Me.txtFKey.Text & ""
            FValue = Me.txtFValue.Text & ""
            FDescription = Me.txtFDescription.Text & ""
            FReadonly = IIf(Me.chkFReadonly.Checked, 1, 0)
            strFReadonly = IIf(Me.chkFReadonly.Checked, "是", "否")

            '類別代碼
            If Me.cmbFCategory.Text.Length <= 0 Then
                MsgBox(GetMsg("SYSTEM", "FCategoryIsNull"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.cmbFCategory.Focus()
                Return False
            End If

            '名稱
            If FKey.Length = 0 Then
                MsgBox(GetMsg("SYSTEM", "FKeyIsNull"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.txtFKey.Focus()
                Return False
            End If

            '設定值
            If FValue.Length = 0 Then
                MsgBox(GetMsg("SYSTEM", "FValueIsNull"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.txtFValue.Focus()
                Return False
            End If

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                sql = "SELECT COUNT(*) FROM BSC_SystemProfile WHERE FCategory='" & FCategory & "' AND FKey='" & FKey & _
                         "'"
                If CInt(GetValue(sql)) > 0 Then
                    MsgBox(GetMsg("SYSTEM", "FValueIsReplace"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.cmbFCategory.Focus()
                    Return False
                End If

            End If

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                OriFCategory = dgv1.CurrentRow.Cells("FCategory").Value & ""
                OriFKey = dgv1.CurrentRow.Cells("FKey").Value & ""
                OriFValue = dgv1.CurrentRow.Cells("FValue").Value & ""

                Try
                    sql = "SELECT * INTO #T1 FROM BSC_SystemProfile ;"
                    sql += " UPDATE #T1 SET FCategory='" & FCategory & "',FKey='" & FKey & "' WHERE  FCategory='" & _
                           OriFCategory & "' AND FKey='" & OriFKey & "';"
                    sql += " SELECT COUNT(*) FROM #T1 WHERE FCategory='" & FCategory & _
                        "' AND FKey='" & FKey & "';"

                    If CInt(GetValue(sql)) > 1 Then
                        MsgBox(GetMsg("SYSTEM", "FValueIsReplace"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.cmbFCategory.Focus()
                        Return False
                    End If

                Catch ex As Exception
                    MsgBox("ActionInitialize：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                End Try

            End If

            Me.Cursor = Cursors.Default

            Return True
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox("ActionInitialize：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)

        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

        Try
            If ActionInitialize() = False Then Exit Function

            If BtnActionSave() = True Then
                IsFind = FindRecord()
                SetButton(ButtonType.Browse, IsFind)
                Return True
            Else
                'IsFind = FindRecord()
                'SetButton(ButtonType.Browse, IsFind)
                
                Return False
            End If
        Catch ex As Exception
            MsgBox("ActionSave:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function
#End Region

#Region "Windows Sub"



    Private Sub Frm_System_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            BindDgv(dgv1, 1)

            With Me.dgv1
                .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .MultiSelect = False
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ReadOnly = True

            End With

            ReBindControls()

            Me.EnabledControls(False)
            ReadDgrdStyle(Me)

            AddToolStripMenuItem(ContextMenuStrip1, dgv1)

        Catch ex As Exception
            MsgBox("Frm_System_Load：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub cmbFCategory1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmbFCategory1.KeyDown, _
                chkFReadonly.KeyDown, txtFKey.KeyDown, txtFValue.KeyDown, cmbFCategory.KeyDown, _
                chkFReadonly1.KeyDown, txtFDescription1.KeyDown, txtFValue1.KeyDown, txtFKey1.KeyDown

        Try
            If e.KeyCode = Keys.Shift Then
                e.Handled = True
                If e.KeyCode = Keys.Enter Then
                    SendKeys.Send("+{TAB}")
                    SendKeys.Send("{F4}")

                End If
            Else
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        SendKeys.Send("{TAB}")

                End Select

            End If

        Catch ex As Exception
            MsgBox("cmbFCategory1_KeyDown：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click
        Filter()

    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        'ActionSave()
        Me.MainFrom.ToolStripSave.Enabled = True
        Me.MainFrom.ToolStripSave.PerformClick()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'ActionCancel()
        Me.MainFrom.ToolStripCancel.Enabled = True
        Me.MainFrom.ToolStripCancel.PerformClick()
    End Sub

    Private Sub mnuSaveStyle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSaveStyle.Click
        SaveDgrdStyle(Me)
    End Sub

    Private Sub mnuDelStyle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDelStyle.Click
        DeldgvStyle(Me)
    End Sub

#End Region

#Region "Function Define"

    ''' <summary>
    ''' 獲取公共資料
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub GetPublic()
        Try

            Dim Table(1) As String
            Dim sql(1) As String

            '系統參數
            Table(0) = "BSC_SystemProfile"
            sql(0) = "SELECT '' FCategory UNION SELECT DISTINCT FCategory FROM BSC_SystemProfile  ORDER BY FCategory"

            '系統參數1
            Table(1) = "BSC_SystemProfile1"
            sql(1) = "SELECT '' FCategory UNION SELECT DISTINCT FCategory FROM BSC_SystemProfile  ORDER BY FCategory"

            dsBSC = GetDataSet(sql, Table)

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 綁定單元格並設定標題
    ''' </summary>
    ''' <param name="dgv"></param>
    ''' <param name="Index"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function BindDgv(ByVal dgv As DataGridView, ByVal Index As Integer)
        Try
            Dim tb As New DataTable
            Dim mTable As New DataTable
            Dim Hash As New Hashtable

            With tb
                .Columns.Add("colName")
                .Columns.Add("colCaption")
            End With

            With tb.Rows
                Select Case Index
                    Case 1
                        .Add("FCategory", "類別")
                        .Add("FKey", "名稱")
                        .Add("FValue", "設定值")
                        .Add("FDescription", "描述")
                        .Add("FReadonly", "是否唯讀")

                    Case 2

                End Select
            End With

            With mTable
                For I As Integer = 0 To tb.Rows.Count - 1
                    .Columns.Add(tb.Rows(I).Item(0))
                Next
            End With

            dgv.DataSource = mTable

            With Hash
                For I As Integer = 0 To tb.Rows.Count - 1
                    Hash.Add(tb.Rows(I).Item(0), tb.Rows(I).Item(1))
                Next
            End With

            For I As Integer = 0 To dgv.Columns.Count - 1
                Dim colName, colCaption As String
                colName = mTable.Columns(I).ColumnName
                dgv.Columns(colName).HeaderText = Hash.Item(colName)
                dgv.Columns(I).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
            Next


        Catch ex As Exception
            MsgBox("BindDgv：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    ''' <summary>
    ''' 過濾符合條件的記錄
    ''' </summary>
    ''' <remarks></remarks>
    Sub Filter()
        Dim Frm As New Frm_Wating
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Exit Sub
            End If

            Frm.Show()

            Dim sql As String = "SELECT FCategory, FKey, FValue, FDescription, " & _
                                "       FReadonly =CASE FReadonly WHEN 1 THEN '是' ELSE '否' END" & _
                                " FROM BSC_SystemProfile WHERE 1=1 "

            If Me.cmbFCategory1.Text <> "" Then
                sql += " AND FCategory='" & Me.cmbFCategory1.Text & "' "
            End If

            If Me.txtFKey1.Text <> "" Then
                sql += " AND FKey LIKE '%" & Me.txtFKey1.Text & "%'"
            End If

            If Me.txtFValue1.Text <> "" Then
                sql += " AND FValue LIKE '%" & Me.txtFValue1.Text & "%'"
            End If

            If Me.txtFDescription1.Text <> "" Then
                sql += " AND FDescription LIKE '%" & Me.txtFDescription1.Text & "%'"

            End If

            If Me.chkFReadonly1.Checked Then
                sql += " AND FReadonly=1 "
            End If
            sql += " ORDER BY FCategory,FKey"


            ds = ReturnDataset(sql)

            dgv1.DataSource = ds.Tables(0)
            Frm.Dispose()

            bFind = (ds.Tables(0).Rows.Count > 0)
            If bFind = False Then
                MsgBox(Msg.NotFindRecord, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If

            dgv1_CurrentCellChanged(Nothing, Nothing)


        Catch ex As Exception
            Frm.Dispose()
            MsgBox("Filter：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)

        Finally
            Frm = Nothing
        End Try


    End Sub

    ''' <summary>
    ''' 重新綁定控制項的資料源
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ReBindControls()
        Try
            GetPublic()

            '綁定數據

            With Me.cmbFCategory1
                .DataSource = dsBSC.Tables("BSC_SystemProfile1")
                .ValueMember = ("FCategory")
                .DisplayMember = ("FCategory")
            End With

            With Me.cmbFCategory
                .DataSource = dsBSC.Tables("BSC_SystemProfile")
                .ValueMember = ("FCategory")
                .DisplayMember = ("FCategory")
            End With


        Catch ex As Exception
            MsgBox("ReBindControls：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try


    End Sub

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type"></param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try
            Select Case type
                Case ButtonType.Add
                    With MainFrom
                        .ToolStripAdd.Enabled = False And AddEnable
                        .ToolStripEdit.Enabled = False And EditEnable
                        .ToolStripDelete.Enabled = False And DeleteEnable
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind And ExportEnable
                        .ToolStripImport.Enabled = True And ImportEnable
                        .ToolStripPrint.Enabled = IsFind And PrintEnable
                        .ToolStripFilter.Enabled = True
                        .ToolStripCheck.Enabled = False
                        .ToolStripUnCheck.Enabled = False

                    End With

                Case ButtonType.Browse
                    With MainFrom
                        .ToolStripAdd.Enabled = True And AddEnable
                        .ToolStripEdit.Enabled = IsFind And EditEnable
                        .ToolStripDelete.Enabled = IsFind And DeleteEnable
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True And ImportEnable
                        .ToolStripPrint.Enabled = IsFind And PrintEnable
                        .ToolStripFilter.Enabled = True
                        .ToolStripCheck.Enabled = False
                        .ToolStripUnCheck.Enabled = False

                    End With

                Case ButtonType.Cancel
                    With MainFrom
                        .ToolStripAdd.Enabled = True And AddEnable
                        .ToolStripEdit.Enabled = IsFind And EditEnable
                        .ToolStripDelete.Enabled = IsFind And DeleteEnable
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True And ImportEnable
                        .ToolStripPrint.Enabled = IsFind And PrintEnable
                        .ToolStripFilter.Enabled = True
                        .ToolStripCheck.Enabled = False
                        .ToolStripUnCheck.Enabled = False

                    End With

                Case ButtonType.Edit
                    With MainFrom
                        .ToolStripAdd.Enabled = False And AddEnable
                        .ToolStripEdit.Enabled = False And EditEnable
                        .ToolStripDelete.Enabled = False And DeleteEnable
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True And ImportEnable
                        .ToolStripPrint.Enabled = IsFind And PrintEnable
                        .ToolStripFilter.Enabled = True
                        .ToolStripCheck.Enabled = False
                        .ToolStripUnCheck.Enabled = False

                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 判斷是否有記錄
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FindRecord() As Boolean

        If ds Is Nothing Then
            Return False
            Exit Function
        End If

        If Me.dgv1.Rows.Count = 0 Then
            Return False
        Else
            Return True

        End If

    End Function

    ''' <summary>
    ''' ClearText
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ClearText()
        Try
            Me.cmbFCategory.Text = ""
            Me.txtFKey.Text = ""
            Me.txtFValue.Text = ""
            Me.txtFDescription.Text = ""
            Me.chkFReadonly.Checked = False
        Catch ex As Exception
            MsgBox("ClearText：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 設置控件的Enable屬性
    ''' </summary>
    ''' <param name="B"></param>
    ''' <remarks></remarks>
    Private Sub EnabledControls(ByVal B As Boolean)
        Try
            Me.GroupBox3.Enabled = B
            dgv1.Enabled = Not B

        Catch ex As Exception
            MsgBox("EnabledControls：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Function BtnActionSave() As Boolean
        Dim cnSqlServer As New SqlConnection
        cnSqlServer = GetConn()
        Dim cmdSqlServer As New SqlCommand
        Dim trnSqlServer As SqlTransaction = cnSqlServer.BeginTransaction

        Try
            Dim sql As String = ""

            Dim FCategory, FKey, FValue, FDescription, strFReadonly As String
            Dim OriFCategory, OriFKey, OriFValue As String
            Dim FReadonly As Int16

            FCategory = Me.cmbFCategory.Text & ""
            FKey = Me.txtFKey.Text & ""
            FValue = Me.txtFValue.Text & ""
            FDescription = Me.txtFDescription.Text & ""
            FReadonly = IIf(Me.chkFReadonly.Checked, 1, 0)
            strFReadonly = IIf(Me.chkFReadonly.Checked, "是", "否")


            '當是添加保存
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then

                With cmdSqlServer
                    .Connection = cnSqlServer
                    .Transaction = trnSqlServer
                    .CommandType = CommandType.Text

                    '向PUR_POA插入記錄
                    .CommandText = "INSERT INTO [BSC_SystemProfile] (FCategory, FKey, FValue, FDescription, FReadonly) VALUES ('" & _
                                   FCategory & "','" & FKey & "','" & FValue & "','" & FDescription & "'," & FReadonly & ")"
                    .ExecuteNonQuery()



                End With

                '增加ds的記錄
                AddtoDataSet(FCategory, FKey, FValue, FDescription, strFReadonly)

            Else

                OriFCategory = dgv1.CurrentRow.Cells("FCategory").Value & ""
                OriFKey = dgv1.CurrentRow.Cells("FKey").Value & ""
                OriFValue = dgv1.CurrentRow.Cells("FValue").Value & ""

                With cmdSqlServer
                    .Connection = cnSqlServer
                    .Transaction = trnSqlServer
                    .CommandType = CommandType.Text


                    '2.更新PUR_POA插入記錄
                    .CommandText = "UPDATE BSC_SystemProfile SET " & _
                      "FCategory='" & FCategory & _
                      "',FKey='" & FKey & _
                      "',FValue='" & FValue & _
                      "',FDescription='" & FDescription & _
                      "',FReadonly=" & FReadonly & _
                      " WHERE FCategory='" & OriFCategory & "' and " & _
                      "FKey='" & OriFKey & "'"

                    .ExecuteNonQuery()

                    For I As Integer = 0 To ds.Tables(0).Rows.Count - 1
                        If ds.Tables(0).Rows(I).Item("FCategory") = OriFCategory And _
                           ds.Tables(0).Rows(I).Item("FKey") = FKey Then
                            ds.Tables(0).Rows(I).Item("FCategory") = FCategory
                            ds.Tables(0).Rows(I).Item("FKey") = FKey
                            ds.Tables(0).Rows(I).Item("FValue") = FValue
                            ds.Tables(0).Rows(I).Item("FDescription") = FDescription
                            ds.Tables(0).Rows(I).Item("FReadonly") = strFReadonly

                        End If
                    Next

                    ds.AcceptChanges()


                    'dgv1.CurrentRow.Cells("FCategory").Value = FCategory
                    'dgv1.CurrentRow.Cells("FKey").Value = FKey
                    'dgv1.CurrentRow.Cells("FValue").Value = FValue
                    'dgv1.CurrentRow.Cells("FDescription").Value = FDescription
                    'dgv1.CurrentRow.Cells("FReadonly").Value = strFReadonly



                End With

            End If
            EnabledControls(False)

            trnSqlServer.Commit()

            MsgBox(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.resources.Addsuccess, My.resources.EditSuccess), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            Me.dgv1_CurrentCellChanged(Nothing, Nothing)
            Return True
        Catch ex As Exception
            trnSqlServer.Rollback()
            MsgBox("BtnActionSave:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Return False


        End Try
    End Function

    ''' <summary>
    ''' AddtoDataSet
    ''' </summary>
    ''' <param name="Remark"></param>
    ''' <remarks></remarks>
    Private Sub AddtoDataSet(ByVal FCategory As String, ByVal FKey As String, ByVal FValue As String, _
                             ByVal FDescription As String, ByVal FReadonly As String)

        Try
            If ds Is Nothing Then
                Initialize()
            End If

            If ds.Tables.Count = 0 Then
                Initialize()
            End If

            Dim mRow As DataRow
            mRow = ds.Tables(0).NewRow
            mRow("FCategory") = FCategory
            mRow("FKey") = FKey
            mRow("FValue") = FValue
            mRow("FDescription") = FDescription
            mRow("FReadonly") = FReadonly

            ds.Tables(0).Rows.Add(mRow)
            ds.Tables(0).AcceptChanges()
        Catch ex As Exception
            MsgBox("AddtoDataSet:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub EditToDataSet(ByVal FCategory As String, ByVal FKey As String, ByVal FValue As String, _
                             ByVal FDescription As String, ByVal FReadonly As String)

        Try
            If ds Is Nothing Then Exit Sub
            Dim Rows() As DataRow = ds.Tables(0).Select("Num='" & strOriginalNum & "'")
            If Rows.Length > 0 Then
                For Each mRow As DataRow In Rows
                    mRow("FCategory") = FCategory
                    mRow("FKey") = FKey
                    mRow("FValue") = FValue
                    mRow("FDescription") = FDescription
                    mRow("FReadonly") = FReadonly

                Next
                ds.AcceptChanges()
            End If
        Catch ex As Exception
            MsgBox("EditToDataSet：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    '''  初始化ds
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Initialize()
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim sql As String = "SELECT FCategory, FKey, FValue, FDescription, " & _
                               "       FReadonly =CASE FReadonly WHEN 1 THEN '是' ELSE '否' END" & _
                               " FROM BSC_SystemProfile WHERE 1=2 "

            ds = ReturnDataset(sql)
            Me.dgv1.DataSource = ds.Tables(0)
            IsFind = FindRecord()
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox("Initialize：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default

        End Try

    End Function

    ''' <summary>
    ''' 為新添加的欄位名稱菜單添加事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Dim mnu As ToolStripMenuItem
            Dim mnuName As String
            mnu = CType(sender, ToolStripMenuItem)
            mnu.Checked = Not mnu.Checked
            mnuName = sender.Name.ToString.Replace("ToolStripMenuItem_", "")
            dgv1.Columns(mnuName).Visible = mnu.Checked

        Catch ex As Exception
            MsgBox("mnu_Click：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 根據DataGridView的列名添加菜單
    ''' </summary>
    ''' <param name="mnu">添加到目標菜單</param>
    ''' <param name="dgv">DataGridView</param>
    ''' <remarks></remarks>
    Private Sub AddToolStripMenuItem(ByVal mnu As ContextMenuStrip, ByVal dgv As DataGridView)
        Try
            For I As Integer = 0 To dgv.Columns.Count - 1
                Dim mToolStripMenuItem As New ToolStripMenuItem
                With mToolStripMenuItem
                    .Name = "ToolStripMenuItem_" + dgv.Columns(I).Name
                    .Text = dgv.Columns(I).HeaderText
                    .Checked = dgv.Columns(I).Visible

                End With
                mnu.Items.Add(mToolStripMenuItem)
                AddHandler mToolStripMenuItem.Click, AddressOf mnu_Click

            Next
        Catch ex As Exception
            MsgBox("AddToolStripMenuItem：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

#End Region

#Region "DataGridView sub"
    Private Sub dgv1_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgv1.RowPostPaint
        AddDgvRowNumber(dgv1, sender, e)
    End Sub

    Private Sub dgv1_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgv1.CurrentCellChanged
        Try
            Me.Cursor = Cursors.WaitCursor
            If Not (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit) Then
                Dim mytb As New DataTable
                Dim sql As String
                Dim Num As String
                If Me.dgv1.DataSource Is Nothing Then
                    Exit Sub
                End If

                If Me.dgv1.SelectedCells.Count <= 0 Then
                    Exit Sub

                End If

                If Me.dgv1.CurrentCell Is Nothing Then
                    Exit Sub
                End If

                Me.cmbFCategory.Text = dgv1.CurrentRow.Cells("FCategory").Value & ""
                Me.txtFKey.Text = dgv1.CurrentRow.Cells("FKey").Value & ""
                Me.txtFValue.Text = dgv1.CurrentRow.Cells("FValue").Value & ""
                Me.txtFDescription.Text = dgv1.CurrentRow.Cells("FDescription").Value & ""
                Me.chkFReadonly.Checked = IIf(dgv1.CurrentRow.Cells("FReadonly").Value = "是", True, False)

                IsFind = FindRecord()
                SetButton(ButtonType.Browse, IsFind)

            End If


        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox("dgv1_CurrentCellChanged：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

#End Region


    Private Sub GroupBox3_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox3.Enter

    End Sub

    Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox1.Enter

    End Sub
End Class
